package com.qingcheng.aop;

import com.qingcheng.dao.ProductlogMapper;
import com.qingcheng.dao.SpuMapper;
import com.qingcheng.pojo.goods.Productlog;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.util.IdWorker;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect //交给spring管理 aop
@Component("spuLog")
public class SpuLog {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private ProductlogMapper productlogMapper;

    @Autowired
    private IdWorker idWorker;

    //环绕
    @Around("execution(* com.qingcheng.service.impl.SpuServiceImpl.*.*(..))")
    public Object log(ProceedingJoinPoint pjp,String id){
        Productlog productLog = new Productlog();
        //记录原有数据
        Spu spu = spuMapper.selectByPrimaryKey(id);
        productLog.setId(idWorker.nextId()+"");
        productLog.setSpuId(id);
        productLog.setAuditor("Admin");
        productLog.setAuditTime(new Date());
        productLog.setIsMarketableBef(spu.getIsMarketable());
        productLog.setStatusBef(spu.getStatus());
        productlogMapper.insertSelective(productLog);

        //继续下一个建议或目标方法调用
        Object proceed = null;
        try {
            proceed=pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        //记录现有数据
        Spu spu1 = spuMapper.selectByPrimaryKey(id);
        productLog.setIsMarketableNow(spu1.getIsMarketable());
        productLog.setStatusNow(spu1.getStatus());
        productlogMapper.updateByPrimaryKeySelective(productLog);

        return proceed;
    }
}
